﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
//Connect tho the database to get some info
using MySql.Data.MySqlClient;

namespace Läxomatic
{
    public partial class Login : Form
    {
        public Login()
        {
            InitializeComponent();
        }
        //Skapar en checksumma och jämför med den lagrade checksumman.
        public bool login(string username, string password)
        {
            SavedData.user = Myskul.checkIntrusion(username);
            Tabell<string> Salt = new Tabell<string>(Myskul.Command("select salt FROM user where loginname= '" + Myskul.checkIntrusion(username) + "';"));
            string checksum = Safety.getHashSha256(Salt.getFirstElement() + username + password, 17);
            Tabell<string> userExist = new Tabell<string>(Myskul.Command("SELECT * FROM user AS u JOIN teacher	AS s ON (s.userId = u.id) WHERE u.checksum = '" + checksum + "'"));
            if (!userExist.isEmpty())
                return true;
            else
                return false;
        }
        //Om det går att logga in, så öppnas en ny form upp
        private void btn_login_Click_1(object sender, EventArgs e)
        {
            if (login(txtuser.Text, txtpass.Text))
            {
                laxomatic Lärarform = new laxomatic();
                Lärarform.Show();
                this.Hide();
            }
            else {
                felInfolbl.Visible = true;
            }
        }
        //Laddar in data som används i MySQL-anslutningen
        private void Login_Load(object sender, EventArgs e)
        {
            SavedData.loginData.Add("server", "Webbins.se");
            SavedData.loginData.Add("database", "johan_johan");
            SavedData.loginData.Add("user", "johan_johan");
            SavedData.loginData.Add("password", "Johan123");

        }
        //Byter fokus om man trycker enter, till nsäta kontroll (två metoder)
        private void txtuser_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                txtpass.Focus();
                e.Handled = true;
            }
        }

        private void txtpass_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                btn_login.Focus();
                e.Handled = true;
            }
        }
    }

 }
